package com.shiyi.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shiyi.common.R;
import com.shiyi.common.WebsocketConstants;
import com.shiyi.common.WebsocketDTO;
import com.shiyi.domain.Apply;
import com.shiyi.domain.Friend;
import com.shiyi.domain.User;
import com.shiyi.exception.BusinessException;
import com.shiyi.handle.WebSocketServer;
import com.shiyi.mapper.ApplyMapper;
import com.shiyi.mapper.FriendMapper;
import com.shiyi.mapper.UserMapper;
import com.shiyi.service.ApplyService;
import com.shiyi.utils.PageUtils;
import com.shiyi.vo.ApplyListVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


/**
 * @author: 拾壹
 * @date: 2023/12/15
 * @describe:
 */
@Service
@RequiredArgsConstructor
public class ApplyServiceImpl extends ServiceImpl<ApplyMapper, Apply> implements ApplyService {

    private final WebSocketServer webSocketServer;

    private final UserMapper userMapper;
    private final FriendMapper friendMapper;

    @Override
    public R selectApplyList(Integer userId) {
        if (userId == null) {
            throw new BusinessException("用户id不能为空");
        }
        Page<ApplyListVO> page = baseMapper.selectApplyList(new Page<>(PageUtils.getPageNo(),PageUtils.getPageSize()),userId);
        return R.success(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insertApply(Apply apply) {

        Friend friend = friendMapper.selectOne(new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId, apply.getSendId()).eq(Friend::getFriendId, apply.getReceiverId()));
        if (!ObjectUtils.isEmpty(friend)) {
            throw new BusinessException("已存在好友关系");
        }

        Apply apply1 = baseMapper.selectOne(new LambdaQueryWrapper<Apply>()
                .eq(Apply::getSendId, apply.getSendId()).eq(Apply::getReceiverId, apply.getReceiverId()));
        if(!ObjectUtils.isEmpty(apply1)) {
            apply1.setStatus(0);
            baseMapper.updateById(apply1);
        }else {
            baseMapper.insert(apply);

        }

        User user = userMapper.selectById(apply.getSendId());
        ApplyListVO applyListVO = ApplyListVO.builder().id(apply.getId()).avatar(user.getAvatar()).nickname(user.getNickname()).status(0).build();

        WebsocketDTO websocket = WebsocketDTO.builder().type(WebsocketConstants.MESSAGE_SYSTEM_NOTICE).senderId(apply.getSendId())
                .receiverId(apply.getReceiverId()).data(JSONUtil.toJsonStr(applyListVO)).build();
        webSocketServer.sendNoticeMessage(websocket);
        return R.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateApply(Apply apply) {
        Apply apply1 = baseMapper.selectById(apply.getId());
        //同意好友 则添加双向的好友列表
        if (apply.getStatus() == 1) {
            Friend friend = Friend.builder().userId(apply1.getSendId()).friendId(apply1.getReceiverId()).build();
            friendMapper.insert(friend);

            Friend friend2 = Friend.builder().userId(apply1.getReceiverId()).friendId(apply1.getSendId()).build();
            friendMapper.insert(friend2);
        }
        apply1.setStatus(apply.getStatus());
        baseMapper.updateById(apply1);
        return R.success();
    }
}
